package service

import (
	"context"
	"duoke/model"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/orm"
	"duoke/utils/redislib"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/os/gtime"
	"time"
)

var ShortWatch = new(shortWatchService)

type shortWatchService struct{}

func (s *shortWatchService) InfoByWhere(value interface{}, field string) (*tables.ShortWatch, error) {
	user := new(tables.ShortWatch)
	has, err := orm.Db.Where(value).Cols(field).Get(user)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("短视频不存在")
	}
	return user, nil
}
func (s *shortWatchService) Save(c *gin.Context, req *model.ShortVideWs) error {
	user, err := Request.User(c)
	if err != nil {
		return err
	}
	var m1 tables.Shortvideo
	get, err := orm.Db.Where("id=?", req.VideoId).Get(&m1)
	if err != nil || !get {
		return errors.New("视频不存在")
	}
	var m tables.ShortWatch
	get, err = orm.Db.Where("from_id=? and user_id=?", req.VideoId, user.Id).Get(&m)
	if err != nil {
		return err
	}
	// 计算出至第一次已经多久
	unix := gtime.Now().Unix()
	redisKey := fmt.Sprintf("short_watch_%d_%d", user.Id, req.VideoId)
	// 判断key是否存在
	val := redislib.Redis.Get(context.Background(), redisKey).Val()
	// 不存在则记录,10分钟后过期
	redislib.Redis.Set(context.Background(), redisKey, unix, 6*time.Second)
	if val == "" {
		m.WatchTime += 0
	} else {
		// 存在则计算 过去多少秒
		unix -= gconv.Int64(val)
		m.WatchTime += float32(unix)
	}
	m.FromId = req.VideoId
	m.UserId = user.Id
	m.SubMchId = m1.SubMchId
	m.Acid = user.Acid
	var isNew int
	if get {
		_, err = orm.Db.Where("from_id=? and user_id=?", req.VideoId, user.Id).Update(&m)
		if err != nil {
			return err
		}
	} else {
		isNew = 1
		_, err = orm.Db.Insert(&m)
		if err != nil {
			return err
		}
	}
	m1.WatchTime = m.WatchTime
	m1.Watch += isNew
	_, err = orm.Db.Where("id=?", req.VideoId).Update(&m1)
	return err
}
func (s *shortWatchService) SaveWatch(c *gin.Context, req *model.ReqId) error {
	user, err := Request.User(c)
	if err != nil {
		return err
	}
	var m1 tables.Shortvideo
	get, err := orm.Db.Where("id=?", req.Id).Get(&m1)
	if err != nil || !get {
		return errors.New("视频不存在")
	}
	var m tables.ShortWatch
	get, err = orm.Db.Where("from_id=? and user_id=?", req.Id, user.Id).Get(&m)
	if err != nil {
		return err
	}
	var isNew int
	m.WatchNumber += 1
	m.FromId = req.Id
	m.UserId = user.Id
	m.SubMchId = m1.SubMchId
	m.Acid = user.Acid
	if get {
		_, err = orm.Db.Where("from_id=?", req.Id).Update(&m)
		if err != nil {
			return err
		}
	} else {
		isNew = 1
		_, err = orm.Db.Insert(&m)
		if err != nil {
			return err
		}
	}
	m1.Watch += isNew
	m1.WatchNumber += 1
	_, err = orm.Db.Where("id=?", req.Id).Update(&m1)
	return err
}
